<template>
  <div v-if="isLocationModalVisible" class="modal">
    <div class="modal-content">
      <span class="close" @click="closeLocationModal">&times;</span>
      <h2>输入位置名称</h2>
      <!-- 新增保存成功提示 -->
      <div v-if="saveSuccess" class="success-message">创建成功</div>
      <!-- 新增保存失败提示 -->
      <div v-if="saveFailed" class="error-message">创建失败，可能已存在</div>
      <form @submit.prevent="submitLocation">
        <label for="locationName">位置名称:</label>
        <input type="text" id="locationName" v-model="locationName" required style="box-sizing: border-box;">
        <button type="submit">提交</button>
      </form>
    </div>
  </div>
</template>

<script>
export default {
  name: 'LocationModal',
  props: {
    isLocationModalVisible: Boolean
  },
  data() {
    return {
      locationName: '',
      saveSuccess: false, // 新增保存成功标志
      saveFailed: false   // 新增保存失败标志
    };
  },
  methods: {
    async submitLocation() {
      try {
        const response = await fetch('/CreateLocation', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ name: this.locationName })
        });
        if (response.ok) {
          console.log('新建位置成功');
          this.saveSuccess = true; // 显示保存成功提示
          this.saveFailed = false; // 隐藏保存失败提示
          setTimeout(() => {
            this.closeLocationModal();
          }, 1000); // 2 秒后关闭模态框
        } else {
          console.error('新建位置失败');
          this.saveSuccess = false; // 隐藏保存成功提示
          this.saveFailed = true;   // 显示保存失败提示
        }
      } catch (error) {
        console.error('请求出错:', error);
        this.saveSuccess = false; // 隐藏保存成功提示
        this.saveFailed = true;   // 显示保存失败提示
      }
    },
    closeLocationModal() {
      this.saveSuccess = false; // 关闭模态框时隐藏保存成功提示
      this.saveFailed = false;  // 关闭模态框时隐藏保存失败提示
      this.$emit('closeLocationModal');
    }
  }
};
</script>

<style scoped>
@import './ModalStyles.css';
/* 新增成功和失败提示样式 */
.success-message {
  color: green;
  margin-bottom: 10px;
}
.error-message {
  color: red;
  margin-bottom: 10px;
}
</style>